package com.drore.app.utils;

import android.text.TextUtils;

import com.drore.app.LogRecordUtil;
import com.drore.www.logbeansecret.AesUtil;
import com.drore.www.logbeansecret.bean.NetConnectBean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * desc
 *
 * @author sixbing
 * @date 2018/11/28 10:41
 */

public class UpLoadUtils {
    private static String TAG = "UpLoadUtils";//    /**
    //     * 数据跟在链接后面，数据大不好用
//     *
//     * @param json
//     * @return
//     * @throws Exception
//     */
//    public static String upLoadJson(String json) throws Exception {
//        String urlPath = new String("http://172.16.10.236:8080/logan/insertLoganList");
//        //String urlPath = new String("http://localhost:8080/Test1/HelloWorld?name=丁丁".getBytes("UTF-8"));
//        //[{"id": 1, "c": "大萨达撒多","f": "12333333333333333333333333333333", "l": "1231232","n": "s","i": 1,"m": "s"}]
//        String param = "" + URLEncoder.encode(json, "UTF-8");
////        String param = RSAUtils.ep
//        //建立连接
//        URL url = new URL(urlPath);
//        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//        //设置参数
//        httpConn.setDoOutput(true);     //需要输出
//        httpConn.setDoInput(true);      //需要输入
//        httpConn.setUseCaches(false);   //不允许缓存
//        httpConn.setRequestMethod("POST");      //设置POST方式连接
//        //设置请求属性
//        httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//        httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
//        httpConn.setRequestProperty("Charset", "UTF-8");
//
//        //连接,也可以不用明文connect，使用下面的httpConn.getOutputStream()会自动connect
//        httpConn.connect();
//
//        //建立输入流，向指向的URL传入参数
//        DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
//        dos.writeBytes(param);
//        dos.flush();
//        dos.close();
//        //获得响应状态
//        int resultCode = httpConn.getResponseCode();
//        StringBuffer sb = new StringBuffer();
//        if (HttpURLConnection.HTTP_OK == resultCode) {
//            String readLine = new String();
//            BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
//            while ((readLine = responseReader.readLine()) != null) {
//                sb.append(readLine).append("\n");
//            }
//            responseReader.close();
//            System.out.println(sb.toString());
//        }
//        return sb.toString();
//    }
    private String Key16 = "0123456789012345";
    private String Iv16 = "0123456789012345";

    //发送JSON字符串 如果成功则返回成功标识。
    public static String doJsonPost(String urlPath, String jsonStr, String password) {
//        Log.e(TAG, jsonStr);
//        password = "0123456789012345";
//        jsonStr = "美女，约吗？";
        byte[] writebytes = new byte[0];
        if (!TextUtils.isEmpty(jsonStr)) {
            try {
//                Log.e(TAG,"\n加密前：" + jsonStr);
//                Log.e(TAG,"加密密钥和解密密钥：" + password);
                String encrypt3 = AesUtil.encrypt(jsonStr, password,password);
//                Log.e(TAG,"加密后：" + encrypt3);
                writebytes=encrypt3.getBytes();
//                String decrypt3 =  AesUtil.getInstance().decrypt(encrypt3, password,password);
//                Log.e(TAG,"解密后：" + decrypt3);
//                Log.e(TAG,"\n\n加密密钥和解密密钥：" + password);
//                String encrypt = AESAndroidUtil.encrypt(jsonStr, password);
//                Log.e(TAG,"加密后：" + encrypt);
//                String decrypt =  AESAndroidUtil.decrypt(encrypt, password);
//                Log.e(TAG,"解密后：" + decrypt);
//                Log.e(TAG,"------------------------------------------------------" );
            } catch (Exception e) {
                e.printStackTrace();
                return "error";
            }
        }
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setConnectTimeout(10000);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
            conn.setRequestProperty("accept", "application/json");
            // 往服务器里面发送数据
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
            OutputStream outwritestream = conn.getOutputStream();
            outwritestream.write(writebytes);
            outwritestream.flush();
            outwritestream.close();
            LogUtils.e("UpLoadUtils", "doJsonPost: getResponseCode():" + conn.getResponseCode());
            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                result = reader.readLine();
            } else {
                result = "" + conn.getResponseCode();
                NetConnectBean netConnectBean = new NetConnectBean();
                netConnectBean.setRequestDetail(conn.getResponseMessage());
                netConnectBean.setRequestCode(conn.getResponseCode());
                netConnectBean.setRequestUrl(urlPath);
                netConnectBean.setSuccess(false);
                netConnectBean.setRequestMethod(conn.getRequestMethod());
                long time = TimeLogUtils.getCurrentTimeInLong();
                netConnectBean.setRequestStartTime(time);
                netConnectBean.setRequestEndTime(time);
                netConnectBean.setRequestDuration(conn.getReadTimeout());
                LogRecordUtil.setNetDetail(netConnectBean, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
